package com.hainatong.jcmvvmbase.utils;

import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

import java.lang.reflect.Type;

/**
 * 字符串和Java类的转换工具
 */
public class GsonUtil
{
    private static final String TAG = "GsonUtil";

    public static String toJson(Object obj)
    {
        String result = createGson().toJson(obj);

        return result;
    }

    private static Gson createGson() {
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.serializeNulls();
        return gsonBuilder.create();
    }


    /**
     * 将字符串转换成对应的Java对象
     */
    public static <T> T fromJSON(String json, Class<T> cls) {
        try {
            return createGson().fromJson(json, cls);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static boolean isJson(String jsonStr)
    {
        JsonElement jsonElement;
        try {
            jsonElement = new JsonParser().parse(jsonStr);
        } catch (Exception e) {
            return false;
        }
        if (jsonElement == null) {
            return false;
        }
        if (!jsonElement.isJsonObject()) {
            return false;
        }
        return true;
    }



    private static Gson gson = new Gson();

    /**
     * 获取一个 可以忽略实体类字段的 Gson
     * 用（@Expose  ） 注解
     * @return
     */
    public static Gson getExposeGson()
    {
        GsonBuilder builder = new GsonBuilder();
        builder.excludeFieldsWithoutExposeAnnotation();
        return builder.create();
    }

    /**
     *
     * @param json jsonStr
     * @param tClass 类型
     * @param <T> 类型
     * @return
     */
    public static <T>T json2Obj(String json , Class<T> tClass)
    {
        T t  = null;
        try {
            t = gson.fromJson(json,tClass);
        }catch (Exception e)
        {
            Log.e(TAG,"Json转换obj出错");
        }
        return t;
    }


    /**
     *
     * @param obj obj
     * @return jsonStr
     */
    public static String obj2json(Object obj)
    {
        String jsonStr = "";
        try {
            jsonStr = gson.toJson(obj);
        }catch (Exception e)
        {
            Log.e(TAG,"Obj转换Json出错");
        }
        return jsonStr;
    }



    public static  <T>T  json2Obj(String json , Type typeOfT)
    {
        T t  = null;

        try {
            t = gson.fromJson(json,typeOfT);
        }catch (Exception e)
        {
            Log.e(TAG,"Json转换obj出错");
        }

        return  t;
    }

}
